package models

import (
	"context"
	"time"

	"github.com/jmoiron/sqlx"
	"learning.com/edu/utils/helper"
)

type Models struct {
	Users 	UserModel
	Tokens  TokenModel
	Courses CourseModel
	Business BusinessModel
}

/**
 * @Description: 创建数据库模型
 * @param {*DatabaseConfig} cfg
 * @param {*helper.Helper} helper
 * @return {*}
 */
func NewModels(cfg *DatabaseConfig, helper *helper.Helper) (*Models, error) {
	db, err := sqlx.Open("postgres", cfg.Dsn())
	if err != nil {
		return nil, err
	}

	db.SetMaxOpenConns(cfg.Maxopenconns) // 最大连接数
	db.SetMaxIdleConns(cfg.Maxidleconns) // 最大空闲数
	db.SetConnMaxLifetime(cfg.MaxidletimeDuration()) // 最大空闲时间

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	err = db.PingContext(ctx)
	if err != nil {
		return nil, err
	}

	return &Models{
		Users: UserModel{DB: db, helper: helper},
		Tokens: TokenModel{DB: db},
		Courses: CourseModel{DB: db},
		Business: BusinessModel{DB: db},
	}, nil
}